package com.shengwei.truck.driver.net;
import android.os.Environment;
import android.text.TextUtils;

import com.shengwei.truck.driver.bean.MyConstant;
import com.shengwei.truck.driver.bean.User;
import com.shengwei.truck.driver.utils.MyLogCat;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 初始化okhttp,retrofit,获取各模块的RetrofitApiService（包含了所有要调用的后台接口的类）
 * 单例模式，只有一个RetrofitManager实例，只有一个okhttpClient实例，只有一个retrofit实例。
 *
 */
public class RetrofitManager {
    private static RetrofitManager retrofitManager;
    private static Retrofit retrofit;
    private OkHttpClient okHttpClient;
    private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create();
    private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJavaCallAdapterFactory.create();
    private static  RetrofitApiService retrofitApiService;
    String TAG = "RetrofitManager";

    /**
     * 获取RetrofitManager单例
     * @return
     */
    public synchronized static RetrofitManager getRetrofitManager() {
        if (retrofitManager == null) {
            synchronized (RetrofitManager.class) {
                if (retrofitManager == null) {
                    retrofitManager = new RetrofitManager();
                }
            }
        }
        return retrofitManager;
    }

    /**
     * 构造函数
     */
    private RetrofitManager() {
        //初始化并生成一个okhttpClient实例
        initOkHttpClient();
        //初始化并生成一个Retrofit实例
        initRetrofit();
    }
    /**
     * 获取Service类：包含了所有后台接口
     * @return
     */
    public static RetrofitApiService getApiService() {
        if (retrofitManager == null) {
            retrofitManager = getRetrofitManager();
        }
        retrofitApiService = retrofit.create(RetrofitApiService.class);
        return retrofitApiService;
    }

    /**
     * 配置okthttpClient的连接参数，如超时时间等
     */
    private void initOkHttpClient() {
        HttpLoggingInterceptor loggingInterceptor = null;
        if (MyConstant.BUILD_TYPE.equals("debug")) {
            loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        }

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                //配置缓存，超时等
                .cache(new Cache(new File(Environment.getExternalStorageDirectory() + "/TruckDriver/"), 50 * 1024 * 1024))
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .callTimeout(30,TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .addInterceptor(loggingInterceptor)
                //拦截器，请求前配置一些公共header或参数等，如Authorization token
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request.Builder requestBuilder = chain.request().newBuilder();
                        requestBuilder.addHeader("Accept-Encoding", "gzip, deflate");
                        requestBuilder.addHeader("Connection", "keep-alive");
                        requestBuilder.addHeader("Accept", "*/*");
                        requestBuilder.addHeader("Content-Type", "application/json;charset=UTF-8");
                        requestBuilder.addHeader("Accept", "application/json");
                        requestBuilder.addHeader("Transfer-Encoding", "chunked");
                        requestBuilder.addHeader("Connection", "close");
                        //请求除登录以外的接口，都要带上token
                        String token = User.getToken();
                        String tokenHead = User.getTokenHead();
                        MyLogCat.i(TAG,"token="+tokenHead+" "+token);
                        if(!TextUtils.isEmpty(token) && !TextUtils.isEmpty(tokenHead)) {
                            requestBuilder.addHeader("Authorization",tokenHead+" "+token);
                        }
                        Request request = requestBuilder.build();
                        return chain.proceed(request);
                    }
                });

                okHttpClient = builder.build();
    }

    /**
     * 初始化并生成一个Retrofit实例
     */
    private void initRetrofit() {
        String baseUrl = null;
        if (MyConstant.BUILD_TYPE.equals("debug")) {
            baseUrl = MyConstant.BUSINESS_SERVER_DEBUG;
        }
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)         //配置接口根路径
                .addConverterFactory(gsonConverterFactory)        //可以解析json
                .addCallAdapterFactory(rxJavaCallAdapterFactory)  //结合Rxjava
                .client(okHttpClient)
                .build();
    }
}
